angular.module("noticeApp", ['ui.bootstrap', 'httpService']).controller("noticeCtrl", ['$scope', '$http', '$uibModal', '$timeout', 'noticeService',
function($scope, $http, $modal, $timeout, noticeService) {

    $scope.addNotice = function() {
        $modal.open({
            templateUrl : "modifyNotice",
            controller : "insertNoticeCtrl"
        });
    };
    $scope.updateNotice = function() {
        if ($scope.checkedIndex == -1) {
            alert("请选择");
            return;
        }
        $modal.open({
            templateUrl : "modifyNotice",
            scope : $scope,
            controller : "updateNoticeCtrl"
        });
    };
    $scope.deleteNotice = function() {

    };
    $scope.refresh = function() {
        noticeService.getAll().then(function(response) {
            $scope.notices = response;
        }, function(response) {
            alert("获取数据失败");
        });
    };
    $scope.refresh();
    $scope.checkedIndex = -1;
    $scope.selectChange = function(index) {
        if ($scope.notices[index].checked == true) {
            $scope.notices[index].checked = false;
        } else {
            $scope.notices[index].checked = true;
        }
        if ($scope.notices[index].checked) {
            $scope.checkedIndex = index;
            return;
        }
        for (var i = 0; i < $scope.notices.length; i++) {
            var item = $scope.notices[i];
            if (item.checked != undefined && item.checked == true) {
                $scope.checkedIndex = i;
                return;
            }
        }
        $scope.checkedIndex = -1;
    };
}]).controller('insertNoticeCtrl', ["$scope", '$uibModalInstance', "noticeService",
function($scope, $uibModalInstance, noticeService) {
    $scope.close = function() {
        $uibModalInstance.close();
    };
    $scope.submit = function() {
        delete $scope.notice['checked'];
        $scope.loading = true;
        noticeService.insert($scope.notice).then(function(result) {
            $scope.submitted = true;
            $scope.loading = false;
            $scope.result = "成功";
        });
    };
}]).controller('updateNoticeCtrl', ["$scope", '$uibModalInstance', "noticeService",
function($scope, $uibModalInstance, noticeService) {

    $scope.notice = $scope.notices[$scope.checkedIndex];
    $scope.close = function() {
        $uibModalInstance.close();
    };
    $scope.submit = function() {
        delete $scope.notice['checked'];
        $scope.loading = true;
        noticeService.update($scope.notice).then(function(result) {
            $scope.submitted = true;
            $scope.loading = false;
            $scope.result = "成功";
        });
    };
}]); 